<template>
  <div class="tour-guide-page">
    <!-- 面包屑导航 -->
    <div class="container mx-auto px-4 py-4">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>导游服务</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
              导游服务
            </h1>
            <p class="text-gray-600 dark:text-gray-400 mt-2">
              专业持证导游，让您的贵港之旅更加精彩
            </p>
          </div>
          <el-button type="warning" @click="handleBeGuide">
            <el-icon class="mr-2"><User /></el-icon>
            成为导游
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div
      class="search-bar bg-gray-50 dark:bg-gray-800/50 border-b border-gray-100 dark:border-gray-700"
    >
      <div class="container mx-auto px-4 py-4">
        <div class="flex items-center gap-4">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索导游姓名/特长"
            :prefix-icon="Search"
            class="!max-w-xs"
          />
          <el-select
            v-model="searchForm.language"
            placeholder="导游语言"
            clearable
            class="!w-32"
          >
            <el-option label="中文" value="chinese" />
            <el-option label="英语" value="english" />
            <el-option label="粤语" value="cantonese" />
          </el-select>
          <el-select
            v-model="searchForm.specialty"
            placeholder="专长领域"
            clearable
            class="!w-32"
          >
            <el-option label="历史文化" value="history" />
            <el-option label="自然风光" value="nature" />
            <el-option label="美食文化" value="food" />
            <el-option label="民俗风情" value="folk" />
            <el-option label="摄影指导" value="photography" />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex gap-8">
        <!-- 左侧筛选 -->
        <div class="w-60 flex-shrink-0">
          <div
            class="filter-card bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 sticky top-4"
          >
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-6">
              筛选条件
            </h3>

            <div class="space-y-6">
              <!-- 从业经验 -->
              <div class="filter-group">
                <h4
                  class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3"
                >
                  从业经验
                </h4>
                <el-radio-group
                  v-model="filters.experience"
                  class="flex flex-col space-y-2"
                >
                  <el-radio label="" class="!flex !m-0">
                    <div class="flex-1 text-left">全部</div>
                  </el-radio>
                  <el-radio label="0-3" class="!flex !m-0">
                    <div class="flex-1 text-left">3年以下</div>
                  </el-radio>
                  <el-radio label="3-5" class="!flex !m-0">
                    <div class="flex-1 text-left">3-5年</div>
                  </el-radio>
                  <el-radio label="5+" class="!flex !m-0">
                    <div class="flex-1 text-left">5年以上</div>
                  </el-radio>
                </el-radio-group>
              </div>

              <!-- 价格区间 -->
              <div class="filter-group">
                <h4
                  class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3"
                >
                  价格区间
                </h4>
                <el-radio-group
                  v-model="filters.priceRange"
                  class="flex flex-col space-y-2"
                >
                  <el-radio label="" class="!flex !m-0">
                    <div class="flex-1 text-left">全部</div>
                  </el-radio>
                  <el-radio label="0-300" class="!flex !m-0">
                    <div class="flex-1 text-left">300元以下</div>
                  </el-radio>
                  <el-radio label="300-500" class="!flex !m-0">
                    <div class="flex-1 text-left">300-500元</div>
                  </el-radio>
                  <el-radio label="500+" class="!flex !m-0">
                    <div class="flex-1 text-left">500元以上</div>
                  </el-radio>
                </el-radio-group>
              </div>

              <!-- 评分要求 -->
              <div class="filter-group">
                <h4
                  class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3"
                >
                  评分要求
                </h4>
                <el-radio-group
                  v-model="filters.rating"
                  class="flex flex-col space-y-2"
                >
                  <el-radio label="" class="!flex !m-0">
                    <div class="flex-1 text-left">全部</div>
                  </el-radio>
                  <el-radio label="4.5" class="!flex !m-0">
                    <div class="flex-1 text-left">4.5分以上</div>
                  </el-radio>
                  <el-radio label="4.0" class="!flex !m-0">
                    <div class="flex-1 text-left">4.0分以上</div>
                  </el-radio>
                  <el-radio label="3.5" class="!flex !m-0">
                    <div class="flex-1 text-left">3.5分以上</div>
                  </el-radio>
                </el-radio-group>
              </div>

              <!-- 排序方式 -->
              <div class="filter-group">
                <h4
                  class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3"
                >
                  排序方式
                </h4>
                <el-radio-group
                  v-model="filters.sort"
                  class="flex flex-col space-y-2"
                >
                  <el-radio label="rating" class="!flex !m-0">
                    <div class="flex-1 text-left">评分最高</div>
                  </el-radio>
                  <el-radio label="price-asc" class="!flex !m-0">
                    <div class="flex-1 text-left">价格从低到高</div>
                  </el-radio>
                  <el-radio label="price-desc" class="!flex !m-0">
                    <div class="flex-1 text-left">价格从高到低</div>
                  </el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧内容 -->
        <div class="flex-1">
          <!-- 导游列表 -->
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div
              v-for="guide in filteredGuides"
              :key="guide.id"
              class="guide-card bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden hover:shadow-lg transition-all duration-300 cursor-pointer"
              @click="router.push(`/tour-guide/${guide.id}`)"
            >
              <div class="relative">
                <el-image
                  :src="'/images/guides/placeholder.jpg'"
                  class="w-full aspect-[4/3] object-cover"
                />
                <div class="absolute top-2 right-2 flex space-x-1">
                  <el-tag
                    v-if="guide.isVerified"
                    type="success"
                    effect="light"
                    size="small"
                    class="!border-0"
                  >
                    <el-icon class="mr-1"><Check /></el-icon>
                    已认证
                  </el-tag>
                  <el-tag
                    v-if="guide.isPopular"
                    type="warning"
                    effect="light"
                    size="small"
                    class="!border-0"
                  >
                    <el-icon class="mr-1"><Star /></el-icon>
                    人气
                  </el-tag>
                </div>
              </div>
              <div class="p-4">
                <div class="flex items-center space-x-3 mb-3">
                  <el-avatar
                    :size="40"
                    src="/images/guides/avatar-placeholder.jpg"
                  />
                  <div>
                    <h3
                      class="text-base font-medium text-gray-900 dark:text-white"
                    >
                      {{ guide.name }}
                    </h3>
                    <div class="flex items-center text-sm text-gray-500">
                      <el-rate v-model="guide.rating" disabled size="small" />
                      <span class="ml-1">{{ guide.rating }}</span>
                    </div>
                  </div>
                </div>
                <div class="space-y-2 mb-3">
                  <div class="flex items-center justify-between text-sm">
                    <span class="text-gray-600">
                      <el-icon class="mr-1"><Timer /></el-icon>
                      {{ guide.experience }}年经验
                    </span>
                    <span class="font-medium text-primary-600">
                      ¥{{ guide.price }}/天
                    </span>
                  </div>
                  <div class="flex items-center text-sm text-gray-600">
                    <el-icon class="mr-1"><ChatRound /></el-icon>
                    {{ guide.languages.join("、") }}
                  </div>
                </div>
                <div class="flex flex-wrap gap-1">
                  <el-tag
                    v-for="tag in guide.specialties"
                    :key="tag"
                    size="small"
                    class="!border-0 !bg-primary-50 !text-primary-600 dark:!bg-primary-900/50 dark:!text-primary-400"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="flex justify-center mt-8">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[12, 24, 36, 48]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import {
  Search,
  Timer,
  ChatRound,
  Location,
  Check,
  Star,
  Compass,
  User,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import service from "@/api/axios"; // 导入axios服务

const router = useRouter();

// 搜索表单
const searchForm = reactive({
  keyword: "",
  language: "",
  specialty: "",
});

// 筛选条件
const filters = reactive({
  experience: "",
  priceRange: "",
  rating: "",
  sort: "rating",
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);

// 导游数据
const guides = ref([
  {
    id: 1,
    name: "李明",
    avatar: new URL(
      "@/assets/images/guides/default-avatar.svg",
      import.meta.url,
    ).href,
    cover: new URL("@/assets/images/guides/default-avatar.svg", import.meta.url)
      .href,
    rating: 4.8,
    reviewCount: 256,
    price: 380,
    experience: 5,
    languages: ["中文", "英语"],
    specialties: ["历史文化", "民俗风情"],
    introduction:
      "从事导游工作5年，对贵港历史文化有深入研究，特别擅长为游客讲解历史故事和民俗文化。",
    isVerified: true,
    isPopular: true,
  },
  {
    id: 2,
    name: "张华",
    avatar: new URL(
      "@/assets/images/guides/default-avatar.svg",
      import.meta.url,
    ).href,
    cover: new URL("@/assets/images/guides/default-avatar.svg", import.meta.url)
      .href,
    rating: 4.9,
    reviewCount: 328,
    price: 450,
    experience: 8,
    languages: ["中文", "粤语"],
    specialties: ["美食文化", "摄影指导"],
    introduction:
      "资深导游，熟悉贵港各大景点，擅长为游客推荐美食和拍照打卡地点。",
    isVerified: true,
    isPopular: true,
  },
  {
    id: 3,
    name: "王丽",
    avatar: new URL(
      "@/assets/images/guides/default-avatar.svg",
      import.meta.url,
    ).href,
    cover: new URL("@/assets/images/guides/default-avatar.svg", import.meta.url)
      .href,
    rating: 4.7,
    reviewCount: 186,
    price: 320,
    experience: 3,
    languages: ["中文", "英语"],
    specialties: ["自然风光", "户外探险"],
    introduction:
      "年轻活力的导游，擅长为年轻游客规划有趣的旅游路线，了解当地网红打卡地。",
    isVerified: true,
    isPopular: false,
  },
]);

// 根据筛选条件过滤导游列表
const filteredGuides = computed(() => {
  let result = [...guides.value];

  // 关键词搜索
  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase();
    result = result.filter(
      (guide) =>
        guide.name.toLowerCase().includes(keyword) ||
        guide.specialties.some((s) => s.toLowerCase().includes(keyword)),
    );
  }

  // 语言筛选
  if (searchForm.language) {
    result = result.filter((guide) =>
      guide.languages.includes(searchForm.language),
    );
  }

  // 专长筛选
  if (searchForm.specialty) {
    result = result.filter((guide) =>
      guide.specialties.includes(searchForm.specialty),
    );
  }

  // 从业经验筛选
  if (filters.experience) {
    const [min, max] = filters.experience.split("-");
    result = result.filter((guide) => {
      if (max === "+") {
        return guide.experience >= Number(min);
      } else {
        return (
          guide.experience >= Number(min) && guide.experience <= Number(max)
        );
      }
    });
  }

  // 价格区间筛选
  if (filters.priceRange) {
    const [min, max] = filters.priceRange.split("-");
    result = result.filter((guide) => {
      if (max === "+") {
        return guide.price >= Number(min);
      } else {
        return guide.price >= Number(min) && guide.price <= Number(max);
      }
    });
  }

  // 评分要求筛选
  if (filters.rating) {
    result = result.filter((guide) => guide.rating >= Number(filters.rating));
  }

  // 排序
  switch (filters.sort) {
    case "rating":
      result.sort((a, b) => b.rating - a.rating);
      break;
    case "price-asc":
      result.sort((a, b) => a.price - b.price);
      break;
    case "price-desc":
      result.sort((a, b) => b.price - a.price);
      break;
  }

  // 处理分页
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  
  return result.slice(startIndex, endIndex);
});

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchGuides();
};

// 处理分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchGuides();
};

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchGuides();
};

// 获取导游列表
const fetchGuides = async () => {
  try {
    // 构建查询参数，移除分页参数
    const params = {
      keyword: searchForm.keyword,
      language: searchForm.language,
      specialty: searchForm.specialty,
      experience: filters.experience,
      priceRange: filters.priceRange,
      rating: filters.rating,
      sort: filters.sort
    };

    // 调用公共API接口获取导游列表
    const response = await service.get('/public/tour-guides', { params });
    
    if (response && response.data) {
      // 将完整数据列表存储在guides
      guides.value = response.data;
      // 更新总数
      total.value = guides.value.length;
    } else {
      // 如果接口没有返回数据或出错，保留测试数据
      total.value = guides.value.length;
    }
  } catch (error) {
    console.error("获取导游列表失败:", error);
    // 出错时使用测试数据
    total.value = guides.value.length;
  }
};

// 处理成为导游
const handleBeGuide = () => {
  // 判断用户是否登录
  const token = localStorage.getItem("token");
  const isLoggedIn = !!token;
  
  if (!isLoggedIn) {
    router.push({
      path: "/login",
      query: { redirect: "/guide-apply" },
    });
    return;
  }
  // 已登录则直接跳转到导游申请页面
  router.push("/guide-apply");
};

// 检查用户是否已认证成为导游
const checkGuideStatus = async () => {
  const token = localStorage.getItem("token");
  if (!token) return;
  
  try {
    // 此接口需要认证，使用普通service
    const response = await service.get('/tour-guides/status');
    
    if (response && response.isGuide) {
      // 如果用户已经是导游，可以显示不同的按钮或内容
      // 这里可以根据实际需求修改
    }
  } catch (error) {
    console.error("检查导游状态失败:", error);
  }
};

// 页面加载时获取数据
onMounted(async () => {
  fetchGuides();
  checkGuideStatus();
});
</script>

<style lang="scss" scoped>
.tour-guide-page {
  min-height: 100vh;
  background-color: theme("colors.gray.50");

  .dark & {
    background-color: theme("colors.gray.900");
  }

  :deep(.el-breadcrumb__item) {
    .el-breadcrumb__inner {
      color: theme("colors.gray.500");
      font-weight: normal;

      &.is-link {
        color: theme("colors.gray.500");

        &:hover {
          color: theme("colors.primary.500");
        }
      }
    }

    &:last-child {
      .el-breadcrumb__inner {
        color: theme("colors.gray.900");
        font-weight: 500;

        .dark & {
          color: theme("colors.white");
        }
      }
    }
  }

  .page-header {
    border-bottom: 1px solid theme("colors.gray.200");

    .dark & {
      border-color: theme("colors.gray.700");
    }
  }

  .search-bar {
    position: sticky;
    top: 0;
    z-index: 10;
    backdrop-filter: blur(8px);
  }

  .guide-card {
    &:hover {
      transform: translateY(-2px);
    }
  }

  :deep(.el-radio) {
    margin-bottom: 0;
    width: 100%;
    padding: 8px 0;
    margin: 0;

    .el-radio__label {
      font-size: theme("fontSize.sm");
      color: theme("colors.gray.600");
      padding-left: 8px;

      .dark & {
        color: theme("colors.gray.400");
      }
    }

    .el-radio__inner {
      margin-top: 2px;
    }
  }

  :deep(.el-rate) {
    .el-rate__icon {
      &.el-icon {
        color: theme("colors.yellow.400");

        .dark & {
          color: theme("colors.yellow.500");
        }
      }
    }
  }
}
</style>
